home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8947 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.2 KB  |  52 lines

  1. Path: radius.mae.cornell.edu!schmidt
  2. From: schmidt@radius.mae.cornell.edu (Peter Schmidt)
  3. Newsgroups: comp.lang.c
  4. Subject: reattaching stdin to fd 0
  5. Date: 7 Mar 1996 17:49:14 GMT
  6. Organization: CU-HSS Program in Biomechanical Engineering
  7. Sender: ps17@cornell.edu (Verified)
  8. Message-ID: <4hn7iq$83b@newsstand.cit.cornell.edu>
  9. NNTP-Posting-Host: radius.mae.cornell.edu
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. I have a problem which I find is very poorly documented.
  13.  
  14. My program attaches stdin to a file, while saving the original stdin, like
  15. this:
  16.  
  17.   char *fn;
  18.   int fd;
  19.  
  20.   if ((fd = open(fn, O_RDONLY)) < 0){
  21.     perror(fn);
  22.     exit(1);
  23.     }
  24.   sin2 = dup(0);
  25.   close(0);
  26.   dup2(fd, 0);
  27.  
  28. then, when it is done reading from the file, I re-attach the original
  29. stdin, like this:
  30.  
  31.   close(0);
  32.   close(fd);
  33.   dup2(sin2, 0);
  34.   close(sin2);
  35.  
  36. After doing this, I can read from the keyboard with 
  37.  
  38.   read(0, linebuf, sizeof(linebuf));
  39.  
  40. but if I use any of the stdlib routines, the program reads garbage.  It
  41. seems that after re-attaching stdin to fd 0, stdin and fd 0 do not point to
  42. the same stream.
  43.  
  44. Any help on getting stdin pointing back to the keyboard would be apreciated.
  45.  
  46. Please e-mail replies to ps17@cornell.edu.
  47.  
  48. Thanks in advance
  49.  
  50.      Peter Schmidt
  51.      ps17@cornell.edu
  52.